package com.kitom.qqmap.api.impl;

import com.kitom.qqmap.api.QQIpLocationService;
import com.kitom.qqmap.api.QQmapGeocodeService;
import com.kitom.qqmap.api.QQmapService;
import com.kitom.qqmap.api.QQmapSearchService;
import com.kitom.qqmap.config.QQmapConfig;
import club.mrxiao.common.utils.StringUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;

/**
 * <pre>
 *  腾讯地图api接口实现
 * </pre>
 * @author <a href="https://gitee.com/kitom">ki_tom</a>
 * @since 2021-01-12
 */
public class QQmapServiceImpl implements QQmapService {

    private QQmapConfig qqmapConfig;
    private QQmapGeocodeService amapGeocodeService = new QQmapGeocodeServiceImpl(this);
    private QQmapSearchService amapWeatherService = new QQmapSearchServiceImpl(this);
    private QQIpLocationService qqIpLocationService = new QQIpLocationServiceImpl(this);


    @Override
    public void setQQmapConfig(QQmapConfig config) {
        this.qqmapConfig = config;
    }

    @Override
    public QQmapGeocodeService getQQmapGeocodeService() {
        return this.amapGeocodeService;
    }

    @Override
    public QQmapSearchService getQQmapSearchService() {
        return this.amapWeatherService;
    }

    @Override
    public QQIpLocationService getQQmapIpLocationService() {
        return qqIpLocationService;
    }

    @Override
    public String get(String url, JSONObject jsonParam) {
        String queryString = this.toQueryString(jsonParam);
        url = urlJoint(url);
        if(StrUtil.isNotBlank(queryString)){
            url = url+queryString;
        }
        String result = HttpUtil.get(url);
        return result;
    }

    private String toQueryString(JSONObject data) {
        StringBuilder queryString = new StringBuilder();
        for (String str:data.keySet()) {
            Object item = data.get(str);
            if (item instanceof String) {
                item = StringUtil.utf8encode(item.toString());
            }
            queryString.append("&").append(str).append("=").append(item);
        }
        return queryString.toString();
    }


    private String urlJoint(String url){
        String key = this.qqmapConfig.getKey();
        if(StrUtil.isBlank(url)){
            throw new IllegalArgumentException("url不能为空");
        }
        if(StrUtil.isBlank(key)){
            throw new IllegalArgumentException("key未配置");
        }
        if (url.contains("key=")) {
            throw new IllegalArgumentException("url参数中不允许有key: " + url);
        }
        return url + (url.contains("?") ? "&" : "?") + "key=" + key+"&output=json";
    }
}
